package com.chenyue.cm.api.live;

import com.alibaba.fastjson.JSON;
import com.alipay.api.internal.util.file.IOUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chenyue.cm.account.domain.JdAccountRecord;
import com.chenyue.cm.account.service.JdAccountRecordService;
import com.chenyue.cm.account.vo.AccountSource;
import com.chenyue.cm.account.vo.ChangeType;
import com.chenyue.cm.auth.Login;
import com.chenyue.cm.auth.LoginUser;
import com.chenyue.cm.auth.token.LoginUserInfo;
import com.chenyue.cm.auth.token.RequestUtil;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.ConstantValues;
import com.chenyue.cm.common.constant.ErrorCode;
import com.chenyue.cm.common.constant.RedisPrefix;
import com.chenyue.cm.common.service.CommonInfoService;
import com.chenyue.cm.common.vo.Page;
import com.chenyue.cm.exception.SysRuntimeException;
import com.chenyue.cm.live.domain.*;
import com.chenyue.cm.live.im.service.ImService;
import com.chenyue.cm.live.service.*;
import com.chenyue.cm.live.vo.*;
import com.chenyue.cm.match.domain.*;
import com.chenyue.cm.match.service.*;
import com.chenyue.cm.match.vo.Address;
import com.chenyue.cm.match.vo.LiveApplyState;
import com.chenyue.cm.msg.service.PushService;
import com.chenyue.cm.tecentCloud.LiveConfig;
import com.chenyue.cm.tecentCloud.LiveRecordAddressUtils;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.user.domain.JdUserCollection;
import com.chenyue.cm.user.domain.JdUserRelation;
import com.chenyue.cm.user.domain.JdVerify;
import com.chenyue.cm.user.service.JdAppUserService;
import com.chenyue.cm.user.service.JdUserCollectionService;
import com.chenyue.cm.user.service.JdUserRelationService;
import com.chenyue.cm.user.service.JdVerifyService;
import com.chenyue.cm.utils.DateUtils;
import com.chenyue.cm.utils.MD5Util;
import com.chenyue.cm.utils.RedisUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author libingxing
 */
@Api(tags = "直播")
@RestController
@RequestMapping("/api/live")
public class ApiLiveController {

    private final JdLiveService liveService;

    private final PushService pushService;

    private final JdAppUserService userService;

    private final JdLiveAgreeService liveAgreeService;

    private final JdLiveRecordService liveRecordService;

    private final CommonInfoService commonInfoService;

    private final JdLiveApplyService liveApplyService;

    private final JdVerifyService verifyService;

    private final JdAccountRecordService accountRecordService;

    private final JdLiveGoldAwardService liveGoldAwardService;

    private final JdUserRelationService userRelationService;

    private final JdMatchService matchService;

    private final JdMatchLiveUserService matchLiveUserService;

    private final JdLiveViewRecordService liveViewRecordService;

    private final RedisUtils redisUtils;

    private final ImService imService;

    private final ViewMatchItemService viewMatchItemService;

    private final JdUserCollectionService userCollectionService;

    private final FormatLiveRecordService formatLiveRecordService;

    private final JdMatchFormatMemberService matchFormatMemberService;

    private final JdMatchScoreRecordService matchScoreRecordService;

    public ApiLiveController(JdLiveService liveService, PushService pushService, JdAppUserService userService, JdLiveAgreeService liveAgreeService, JdLiveRecordService liveRecordService, CommonInfoService commonInfoService, JdLiveApplyService liveApplyService, JdVerifyService verifyService, JdAccountRecordService accountRecordService, JdLiveGoldAwardService liveGoldAwardService, JdUserRelationService userRelationService, JdMatchService matchService, JdMatchLiveUserService matchLiveUserService, JdLiveViewRecordService liveViewRecordService, RedisUtils redisUtils, ImService imService, ViewMatchItemService viewMatchItemService, JdUserCollectionService userCollectionService, FormatLiveRecordService formatLiveRecordService, JdMatchFormatMemberService matchFormatMemberService, JdMatchScoreRecordService matchScoreRecordService) {
        this.liveService = liveService;
        this.pushService = pushService;
        this.userService = userService;
        this.liveAgreeService = liveAgreeService;
        this.liveRecordService = liveRecordService;
        this.commonInfoService = commonInfoService;
        this.liveApplyService = liveApplyService;
        this.verifyService = verifyService;
        this.accountRecordService = accountRecordService;
        this.liveGoldAwardService = liveGoldAwardService;
        this.userRelationService = userRelationService;
        this.matchService = matchService;
        this.matchLiveUserService = matchLiveUserService;
        this.liveViewRecordService = liveViewRecordService;
        this.redisUtils = redisUtils;
        this.imService = imService;
        this.viewMatchItemService = viewMatchItemService;
        this.userCollectionService = userCollectionService;
        this.formatLiveRecordService = formatLiveRecordService;
        this.matchFormatMemberService = matchFormatMemberService;
        this.matchScoreRecordService = matchScoreRecordService;
    }

    @GetMapping("/liveUserList")
    @ApiOperation("主播列表")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页数", name = "page", dataType = "string", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "string", required = true),
            @ApiImplicitParam(value = "主播类型 1赛事主播 2普通主播", name = "type", dataType = "string", required = true),
//            @ApiImplicitParam(value = "直播状态 0未开播 1正在播 2已结束", name = "liveState", dataType = "string", required = true),
    })
    public Success<Page<List<JdLive>>> liveUserList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows,
            Integer type
    ) {
        LambdaQueryWrapper<JdLive> eq = new QueryWrapper<JdLive>().lambda()
                .eq(JdLive::getType, type);
        int count = liveService.count(eq);
        Page<List<JdLive>> result = new Page<>(page, rows, count);
        List<JdLive> list = liveService.list(eq.last(result.convertPage()));
        result.setContent(list);
        return Success.success(result);
    }

    @GetMapping("/liveList")
    @ApiOperation("直播列表")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页数", name = "page", dataType = "string", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "string", required = true),
            @ApiImplicitParam(value = "赛事分类", name = "matchType", dataType = "integer", required = true),
            @ApiImplicitParam(value = "1关注2热门3最新", name = "state", dataType = "integer", required = true),
            @ApiImplicitParam(value = "区域编码", name = "city", dataType = "integer", required = true),
//            @ApiImplicitParam(value = "直播状态 0未开播 1正在播 2已结束", name = "liveState", dataType = "string", required = true),
    })
    public Success<Page<List<LiveList>>> liveList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows,
            Integer liveState,
            Integer matchType, Integer state, Integer city,
            HttpServletRequest request
    ) {
        int userId = 0;
        try {
            final LoginUserInfo loginUser = RequestUtil.getUserInfoByRequest(request);
            userId = loginUser.getUserId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Address address = new Address();
        if (city != null && city > 0) {
            address = commonInfoService.getAddressByArea(city);
        }
        int count = liveRecordService.liveListCount(liveState, matchType, state, userId, address.getCity(), address.getProvince());
        Page<List<LiveList>> result = new Page<>(page, rows, count);
        List<LiveList> list = liveRecordService.liveList(1, matchType, result.convertPage(), state, userId, address.getCity(), address.getProvince());
        for (LiveList liveList : list) {
            try {
                final String currentGroupMemberNumber = imService.getCurrentGroupMemberNumber(liveList.getId() + "");
                if (StringUtils.isNotBlank(currentGroupMemberNumber)) {
                    liveList.setOnlineCount(Integer.parseInt(currentGroupMemberNumber) - 1);
                } else {
                    liveList.setOnlineCount(0);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (rows > list.size()) {
            rows = rows - list.size();
            List<LiveList> newList = liveRecordService.liveList(-1, matchType, result.convertPage(page, rows), state, userId, address.getCity(), address.getProvince());
            list.addAll(newList);
        }
        result.setContent(list);
        return Success.success(result);
    }

    @Login
    @GetMapping("/getLiveAbleRoom")
    @ApiOperation("获取可直播的recordId")
    public Success<LiveInfo> getLiveAbleRoom(
            @LoginUser @ApiIgnore JdAppUser user
    ) {
        final JdLive live = liveService.lambdaQuery().eq(JdLive::getUserId, user.getId()).one();
        if (live == null) {
            return Success.error("您还不是主播");
        }
        final FormatLiveRecord formatLiveRecord = formatLiveRecordService.lambdaQuery()
                .gt(FormatLiveRecord::getMatchEndTime, DateUtils.getToday())
                .lt(FormatLiveRecord::getMatchStartTime, DateUtils.getToday())
                .eq(FormatLiveRecord::getLiveId, live.getId())
                .gt(FormatLiveRecord::getMatchId, 0)
                .orderByAsc(FormatLiveRecord::getStartTime)
                .last(" limit 1").one();
        if (formatLiveRecord == null) {
            return Success.error("尚未给您分配直播间");
        }
        final JdLiveRecord record = liveRecordService.getById(formatLiveRecord.getId());
        //        赛事详情
        final MatchInfo matchInfo = matchService.matchInfo(record.getMatchId(), null);
        LiveInfo liveInfo = new LiveInfo();
        liveInfo.setLiveRecord(record);
        liveInfo.setMatchInfo(matchInfo);
        final Integer fansCount = userRelationService.getFansCount(Integer.valueOf(user.getId()));
        liveInfo.setFansCount(fansCount);
        return Success.success(liveInfo);
    }

    @Login
    @GetMapping("/enterLiveRoomAble")
    @ApiOperation("判断当前登录用户是否有连麦权限")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "直播记录id", name = "recordId", dataType = "string", required = true)
    })
    public Success<String> enterLiveRoomAble(
            @LoginUser @ApiIgnore JdAppUser user, Integer recordId
    ) {
        final JdMatchLiveUser one = matchLiveUserService.lambdaQuery()
                .eq(JdMatchLiveUser::getLiveRecordId, recordId)
                .eq(JdMatchLiveUser::getUserId, user.getId())
                .last(" limit 1 ")
                .one();
        if (one == null) {
            return Success.error("不能连麦");
        }
        final JdMatch match = matchService.getById(one.getMatchId());
        if (match.getMatchType() == 1) {
            final JdMatchScoreRecord record = matchScoreRecordService.lambdaQuery()
                    .eq(JdMatchScoreRecord::getFormatId, one.getFormatId())
                    .eq(JdMatchScoreRecord::getUserId, one.getUserId())
                    .eq(JdMatchScoreRecord::getGroupId, one.getGroupId())
                    .last(" limit 1 ")
                    .one();
//            参赛类型（1单人单项/2单人多项/3多人多项）
            if (record != null) {
                return Success.error("您已经参赛过了");
            }
        }else {
//            2单人多项/3多人多项
            final ViewMatchItem matchItem = viewMatchItemService.getById(match.getId());
            final String[] items = matchItem.getItemIds().split(",");
            final List<JdMatchScoreRecord> record = matchScoreRecordService.lambdaQuery()
                    .eq(JdMatchScoreRecord::getFormatId, one.getFormatId())
                    .eq(JdMatchScoreRecord::getUserId, one.getUserId())
                    .eq(JdMatchScoreRecord::getGroupId, one.getGroupId())
                    .list();
            if (record.size() >= items.length) {
                return Success.error("您已经参赛过了");
            }
        }
        return Success.success();
    }

    @RequestMapping("/clearLive")
    public Success<String> clearLive(Integer recordId) {
        JdLiveRecord live = new JdLiveRecord();
        live.setId(recordId);
        live.setStartTime(null);
        live.setEndTime(null);
        liveRecordService.updateById(live);
        return Success.success();
    }

    @Login
    @GetMapping("/isBanSendMsg")
    @ApiOperation("查看用户是否禁言 1禁言了2没禁言")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "记录id", name = "recordId", dataType = "int", required = true),
    })
    public Success<Integer> clearLive(
            @LoginUser @ApiIgnore JdAppUser user, Integer recordId
    ) {
        return imService.isBanSendMsg(Integer.valueOf(user.getId()), recordId) ? Success.success(1) : Success.success(2);
    }

    @Login
    @PostMapping("/startLive")
    @ApiOperation("开始直播")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "直播记录id", name = "recordId", dataType = "integer", required = true),
            @ApiImplicitParam(value = "直播标题", name = "title", dataType = "string", required = true),
            @ApiImplicitParam(value = "直播封面", name = "cover", dataType = "string", required = true)
    })
    public Success<LiveInfo> startLive(
            @ApiIgnore @LoginUser JdAppUser user,
            String title, Integer recordId, String cover
    ) {
        LambdaQueryWrapper<JdLive> eq = new QueryWrapper<JdLive>().lambda()
                .eq(JdLive::getUserId, user.getId()).last("limit 1");
        JdLive one = liveService.getOne(eq);
        JdLiveRecord record;
        boolean flag;
        LiveAddress addressUrl;
        if (recordId != null && recordId > 0) {
            addressUrl = LiveRecordAddressUtils.getAddressUrl(recordId + "", ConstantValues.ONE_DAY_SEC);
            record = liveRecordService.lambdaQuery().eq(JdLiveRecord::getId, recordId).one();
            convertLiveInfo(title, cover, record, addressUrl);
            flag = liveRecordService.update(
                    record, new LambdaUpdateWrapper<JdLiveRecord>()
                            .eq(JdLiveRecord::getId, recordId)
                            .set(JdLiveRecord::getStartTime, new Date())
                            .set(JdLiveRecord::getEndTime, null)
            );
        } else {
            record = new JdLiveRecord();
            record.setMatchId(0);
            record.setArrangeId(0);
            record.setLiveId(one.getId());
            flag = liveRecordService.save(record);
            if (!flag) {
                throw new SysRuntimeException("开播失败");
            }
            addressUrl = LiveRecordAddressUtils.getAddressUrl(record.getId() + "", ConstantValues.ONE_DAY_SEC);
            convertLiveInfo(title, cover, record, addressUrl);
            flag = liveRecordService.updateById(record);
        }
        final LiveInfo liveInfo = new LiveInfo();
//        直播记录
        liveInfo.setLiveRecord(record);
//        主播信息
        liveInfo.setLive(one);
//        直播地址
        liveInfo.setLiveAddress(addressUrl);
        JdLiveGoldAward goldAward = liveGoldAwardService.lambdaQuery().eq(JdLiveGoldAward::getLiveRecordId, recordId).last(" limit 1").one();
//        红包分配
        liveInfo.setGoldAward(goldAward);
        return flag ? Success.success(liveInfo) : Success.error(ErrorCode.UPDATE_ERROR.getMsg());
    }

    private void convertLiveInfo(String title, String cover, JdLiveRecord record, LiveAddress addressUrl) {
        record.setTitle(title);
        record.setLiveLogo(cover);
        record.setStartTime(Calendar.getInstance().getTime());
        record.setM3u8PullUrl(addressUrl.getPullM3U8());
        record.setFlvPullUrl(addressUrl.getPullFLV());
        record.setRtmpPullUrl(addressUrl.getPullRTMP());
        record.setUdpPullUrl(addressUrl.getPullUDP());
    }

    @PostMapping("/CreateCommonMixStream")
    @ApiOperation("创建通用混流")
    public Success<String> createCommonMixStream(
            @ApiParam @RequestBody MixStreamParam mixStreamParam
    ) {
        return Success.success(liveService.createCommonMixStream(mixStreamParam));
    }

    @Login
    @PostMapping("/createStreamByUser")
    @ApiOperation("根据当前登录用户生成推流地址")
    public Success<LiveAddress> createStreamByUser(
            @ApiIgnore @LoginUser JdAppUser user, Integer liveRecordId
    ) {
        String streamName = "" + user.getId();
        final FormatLiveRecord record = formatLiveRecordService.getById(liveRecordId);
        if (record != null) {
            JdMatchFormatMember formatMember = matchFormatMemberService.lambdaQuery().eq(JdMatchFormatMember::getFormatId, record.getArrangeId()).eq(JdMatchFormatMember::getUserId, user.getId()).one();
            if (formatMember != null) {
                streamName = "CONCAT_" + formatMember.getId();
            }
        }
        final LiveAddress addressUrl = LiveRecordAddressUtils.getAddressUrl(streamName, 8640000);
        logger.info(JSON.toJSONString(addressUrl));
        return Success.success(addressUrl);
    }

    @PostMapping("/addLiveUser")
    @ApiOperation("新增连麦人")
    public Success<String> addLiveUser(
            @ApiParam @RequestBody LiveUserRedis liveUserRedis
    ) {
        redisUtils.operationLiveUser(liveUserRedis, 1);
        saveViewRecord(liveUserRedis.getRecordId(), liveUserRedis.getUserId(), 1);
        return Success.success();
    }

    @PostMapping("/editLiveUser")
    @ApiOperation("编辑连麦人")
    public Success<String> editLiveUser(
            @ApiParam @RequestBody LiveUserRedis liveUserRedis
    ) {
        redisUtils.operationLiveUser(liveUserRedis, 4);
        return Success.success();
    }

    @PostMapping("/deleteLiveUser")
    @ApiOperation("删除连麦人")
    public Success<String> deleteLiveUser(
            @ApiParam @RequestBody LiveUserRedis liveUserRedis
    ) {
        redisUtils.operationLiveUser(liveUserRedis, 2);
        return Success.success();
    }

    @PostMapping("/matchLiveUserList")
    @ApiOperation("连麦人列表")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "直播记录id", name = "recordId", dataType = "string", required = true)
    })
    public Success<List<LiveUserRedis>> liveUserList(
            Integer recordId
    ) {
        final String s = redisUtils.get(RedisPrefix.LIVE_USER + recordId);
        List<LiveUserRedis> idList = new ArrayList<>();
        if (StringUtils.isNotBlank(s)) {
            try {
                idList = JSON.parseArray(s, LiveUserRedis.class);
                for (LiveUserRedis userRedis : idList) {
                    userRedis.setCurrent(System.currentTimeMillis() / 1000);
                }
                System.err.println(s);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Success.success(idList);
    }

//    回调 删除连麦人

    @Login
    @PostMapping("/endLive")
    @ApiOperation("关播")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "直播记录id", name = "recordId", dataType = "integer", required = true)
    })
    public Success<EndLiveResult> endLive(
            Integer recordId
    ) {
        final EndLiveResult result = new EndLiveResult();
        final JdLiveRecord one = liveRecordService.lambdaQuery().eq(JdLiveRecord::getId, recordId).one();
//        删除连麦人
        LiveUserRedis record = new LiveUserRedis();
        record.setRecordId(recordId);
        redisUtils.operationLiveUser(record, 3);
//        统计新增粉丝
        final Integer count = userRelationService.lambdaQuery()
                .ge(JdUserRelation::getCt, one.getStartTime())
                .le(JdUserRelation::getCt, one.getEndTime())
                .count();
        result.setNewFansCount(count);
        //        更新直播结束时间
        final Date now = Calendar.getInstance().getTime();
        one.setEndTime(now);
        liveRecordService.updateById(one);
//        计算直播时间
        result.setLiveDuration((one.getEndTime().getTime() - one.getStartTime().getTime()) / 1000);
        return Success.success(result);
    }

    private final Logger logger = LoggerFactory.getLogger(ApiLiveController.class);

    @RequestMapping("/liveCallBack")
    public void liveCallBack(
            HttpServletRequest request
    ) throws Exception {
        //HTTP POST 请求，包体内容为 JSON
        ServletInputStream in = request.getInputStream();
        //把流转化成字符串
        String content = IOUtils.toString(in, StandardCharsets.UTF_8);
        logger.info("=====================进入回调==========================");
        logger.info(content);
        logger.info("=====================回调参数==========================");
        //获取参数
        LiveCallBackVo liveCallBackVo = JSON.parseObject(content, LiveCallBackVo.class);
        //后台服务器在收到通知消息后可以根据同样的算法确认 sign 是否正确，进而确认消息是否确实来自腾讯云后台。
        if (liveCallBackVo != null) {
            //后台服务器在收到通知消息后可以根据同样的算法确认 sign 是否正确，进而确认消息是否确实来自腾讯云后台。
            String md5 = MD5Util.getMD5(LiveConfig.CALL_BACK_KEY + liveCallBackVo.getT(), false, 32);
            if (!md5.equals(liveCallBackVo.getSign())) {
                logger.info("=====================验签失败==========================");
                return;
            }
            //处理推断流业务
            if (StringUtils.isNotBlank(liveCallBackVo.getChannel_id())) {
                //查询该直播间是否存在
                JdLiveRecord live = liveRecordService.getById(liveCallBackVo.getChannel_id());
                if (live != null) {
                    final Date now = DateUtils.getToday();
                    if (StringUtils.isNotBlank(liveCallBackVo.getEvent_type())) {
                        if ("0".equals(liveCallBackVo.getEvent_type())) {
                            //如果是断流回调
                            if (live.getEndTime() == null) {
                                live.setEndTime(now);
                                liveRecordService.updateById(live);
                                //        删除连麦人
                                LiveUserRedis record = new LiveUserRedis();
                                record.setRecordId(live.getId());
                                redisUtils.operationLiveUser(record, 3);
                            }
                            logger.info("进入断流--------------------------------------------");
                        } else if ("1".equals(liveCallBackVo.getEvent_type())) {
                            //如果是推流回调
                            live.setStartTime(now);
                            liveRecordService.update(
                                    live, new LambdaUpdateWrapper<JdLiveRecord>()
                                            .eq(JdLiveRecord::getId, live.getId())
                                            .set(JdLiveRecord::getEndTime, null)
                            );
                            logger.info("进入推流--------------------------------------------");
                            try {
                                pushService.liveStartPush(live);
                            } catch (Exception ignore) {
                                logger.info("推送异常--------------------------------------------");
                            }
                        } else if ("100".equals(liveCallBackVo.getEvent_type())) {
                            //直播录制
                            if (StringUtils.isEmpty(live.getVideoUrl())) {
                                //存视频地址
                                live.setVideoUrl(liveCallBackVo.getVideo_url());
                            } else {
                                live.setVideoUrl(live.getVideoUrl() + "," + liveCallBackVo.getVideo_url());
                            }
                            liveRecordService.updateById(live);
                            logger.info("进入录制--------------------------------------------");
                        }
                    }
                } else {
//                    连麦人录制
                    final JdMatchFormatMember formatMember = matchFormatMemberService.getById(liveCallBackVo.getChannel_id().split("_")[1]);
                    if (formatMember != null) {
                        if ("0".equals(liveCallBackVo.getEvent_type())) {
                            logger.info("---------------------连麦人断流--------------------");
                        }
                        if ("1".equals(liveCallBackVo.getEvent_type())) {
                            logger.info("---------------------连麦人推流--------------------");
                        }
                        if ("100".equals(liveCallBackVo.getEvent_type())) {
                            //直播录制
                            if (StringUtils.isEmpty(formatMember.getVideoUrl())) {
                                //存视频地址
                                formatMember.setVideoUrl(liveCallBackVo.getVideo_url());
                            } else {
                                formatMember.setVideoUrl(formatMember.getVideoUrl() + "," + liveCallBackVo.getVideo_url());
                            }
                            matchFormatMemberService.updateById(formatMember);
                            logger.info("进入连麦人录制--------------------------------------------");
                        }
                    }
                }
            }

        }
    }

    @GetMapping("/liveInfo")
    @ApiOperation("主播详情")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "主播id", name = "liveId", dataType = "string", required = true),
            @ApiImplicitParam(value = "当前登录用户", name = "currentUser", dataType = "string", required = true),
            @ApiImplicitParam(value = "直播记录id", name = "recordId", dataType = "string", required = true),
    })
    public Success<LiveInfo> liveInfo(
            Integer liveId, Integer currentUser, Integer recordId
    ) {
        final JdLive jdLive = liveService.selectByPrimaryKey(liveId + "");
        final JdAppUser user = userService.selectByPrimaryKey(jdLive.getUserId() + "");
        final LiveInfo liveInfo = new LiveInfo();
        liveInfo.setLive(jdLive);
        liveInfo.setHeadImg(user.getHeadImg());
        liveInfo.setUserName(user.getUserName());
        liveInfo.setIsRelation(userRelationService.isRelation(currentUser, Integer.valueOf(user.getId())));
        liveInfo.setUser(user);
        if (recordId != null && recordId > 0) {
            final JdLiveRecord one = liveRecordService.lambdaQuery().eq(JdLiveRecord::getId, recordId).one();
//            赛事详情
            final MatchInfo matchInfo = matchService.matchInfo(one.getMatchId(), null);
            liveInfo.setMatchInfo(matchInfo);
            JdLiveGoldAward goldAward = liveGoldAwardService.lambdaQuery().eq(JdLiveGoldAward::getLiveRecordId, recordId).last(" limit 1").one();
//            红包分配
            liveInfo.setGoldAward(goldAward);
        }
        if (currentUser != null && currentUser > 0) {
            final JdUserCollection collection = userCollectionService.lambdaQuery()
                    .eq(JdUserCollection::getUserId, currentUser)
                    .eq(JdUserCollection::getColType, 1)
                    .eq(JdUserCollection::getColId, recordId)
                    .one();
            liveInfo.setIsCollect(collection == null ? 2 : 1);
            final JdLiveAgree liveAgree = liveAgreeService.lambdaQuery()
                    .eq(JdLiveAgree::getUserId, currentUser)
                    .eq(JdLiveAgree::getLiveId, liveId)
                    .one();
            liveInfo.setIsAgree(liveAgree == null ? 2 : 1);
            final Integer fansCount = userRelationService.getFansCount(Integer.valueOf(user.getId()));
            liveInfo.setFansCount(fansCount);

            if (recordId != null && recordId > 0) {
                JdAccountRecord amount = accountRecordService.getOne(
                        new LambdaQueryWrapper<JdAccountRecord>()
                                .eq(JdAccountRecord::getSource, AccountSource.GOLD_AWARD)
                                .eq(JdAccountRecord::getOrderId, recordId)
                                .eq(JdAccountRecord::getUserId, currentUser)
                                .last("limit 1")
                );
                liveInfo.setHasGetGold(amount == null ? 2 : 1);
            } else {
                liveInfo.setHasGetGold(2);
            }
        } else {
            liveInfo.setIsCollect(2);
            liveInfo.setFansCount(0);
            liveInfo.setIsAgree(2);
            liveInfo.setHasGetGold(2);
        }

        return Success.success(liveInfo);
    }

    @GetMapping("/liveUserInfo")
    @ApiOperation("参赛员详情")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "参赛员id", name = "userId", dataType = "string", required = true)
    })
    public Success<LiveUserInfo> liveUserInfo(
            Integer currentUser, Integer userId
    ) {
        final JdAppUser user = userService.lambdaQuery().eq(JdAppUser::getId, userId).one();
        final LiveUserInfo userInfo = new LiveUserInfo();
        userInfo.setUserNum(user.getUserNum());
        userInfo.setUserName(user.getUserName());
        userInfo.setSpeciality(user.getSpeciality());
        userInfo.setHistoryRecord(matchLiveUserService.historyRecord(Integer.valueOf(user.getId())));
        userInfo.setHistoryRank(matchLiveUserService.historyRank(Integer.valueOf(user.getId())));
        userInfo.setHeadImg(user.getHeadImg());
        if (currentUser != null && currentUser > 0) {
            userInfo.setIsRelation(userRelationService.isRelation(currentUser, userId));
        } else {
            userInfo.setIsRelation(2);
        }
        return Success.success(userInfo);
    }

    @GetMapping("/liveUserMatchHistory")
    @ApiOperation("参赛员参赛历史")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "参赛员id", name = "userId", dataType = "string", required = true),
            @ApiImplicitParam(value = "页数", name = "page", dataType = "integer", required = true),
            @ApiImplicitParam(value = "页码", name = "rows", dataType = "integer", required = true)
    })
    public Success<Page<List<LiveUserMatchHistory>>> liveUserMatchHistory(
            Integer userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows
    ) {
        Integer total = matchLiveUserService.liveUserMatchHistoryCount(userId);
        final Page<List<LiveUserMatchHistory>> result = new Page<>(page, rows, total);
        List<LiveUserMatchHistory> history = matchLiveUserService.liveUserMatchHistoryList(userId, result.convertPage());
        result.setContent(history);
        return Success.success(result);
    }

    @Login
    @GetMapping("/getGold")
    @ApiOperation("直播间抢金币")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "直播记录id", name = "liveRecordId", dataType = "integer", required = true)
    })
    public Success<Object> getGold(
            @ApiIgnore @LoginUser JdAppUser user,
            Integer liveRecordId
    ) {
        JdLiveGoldAward one = liveGoldAwardService.lambdaQuery().eq(JdLiveGoldAward::getLiveRecordId, liveRecordId).last("limit 1").one();
        if (one == null) {
            return Success.error("已抢完");
        }
        JdAccountRecord amount = accountRecordService.getOne(
                new QueryWrapper<JdAccountRecord>()
                        .select("sum(amount) as amount")
                        .lambda()
                        .eq(JdAccountRecord::getSource, AccountSource.GOLD_AWARD)
                        .eq(JdAccountRecord::getOrderId, liveRecordId)
                        .last("limit 1")
        );
        if (one.getGetTime().after(Calendar.getInstance().getTime())) {
//            还不到发红包的点
            return Success.error("未到时间");
        }
        if (amount != null) {
            if (one.getGoldAmount() - amount.getAmount() < one.getOnceAmount()) {
                return Success.error("已抢完");
            }
        }
        JdAccountRecord record = new JdAccountRecord();
        record.setUserId(Integer.valueOf(user.getId()));
        record.setSource(AccountSource.GOLD_AWARD);
        record.setOrderId(liveRecordId);
        record.setAmount(Double.valueOf(one.getOnceAmount()));
        record.setChangeType(ChangeType.INCOME);
        record.setCt(DateUtils.getToday());
        final boolean save = accountRecordService.save(record);
        return save ? Success.success(one.getOnceAmount()) : Success.error("已抢完");
    }

    /**
     * 进入直播间 保存观看记录
     */
    @PostMapping("/enterLive")
    @ApiOperation("进入直播间")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "直播记录id", name = "recordId", dataType = "string", required = true)
    })
    public Success<FormatLiveRecord> enterLive(
            Integer recordId, HttpServletRequest request
    ) {
        JdAppUser user = new JdAppUser();
        try {
            final LoginUserInfo userInfo = RequestUtil.getUserInfoByRequest(request);
            user = userService.getById(userInfo.getUserId());
        } catch (Exception ignored) {
        }
        final FormatLiveRecord liveRecord = saveViewRecord(recordId, Integer.valueOf(user.getId()), 0);
        liveRecord.setUserId(Integer.valueOf(user.getId()));
        liveRecord.setUserName(user.getUserName());
        final JdMatch match = matchService.getById(liveRecord.getMatchId());
        if (match != null && (user.getId() != null && Integer.parseInt(user.getId().toString()) > 0)) {
            liveRecord.setMatchGroup(match.getMatchGroup());
            ViewMatchGroupUser matchGroupUser = matchService.getGroupByUser(match.getId(), Integer.valueOf(user.getId()));
            if (matchGroupUser != null) {
                liveRecord.setGroupName(matchGroupUser.getName());
            }
        }
        return Success.success(liveRecord);
    }

    private FormatLiveRecord saveViewRecord(Integer recordId, Integer userId, Integer isConcat) {
        final FormatLiveRecord liveRecord = formatLiveRecordService.getById(recordId + "");
        if (liveRecord == null) {
            throw new SysRuntimeException("直播走丢了~");
        }
        if (userId != null && userId > 0) {
            JdLiveViewRecord record = new JdLiveViewRecord();
            record.setLiveRecordId(recordId);
            record.setCt(Calendar.getInstance().getTime());
            record.setUserId(userId);
            record.setIsConcat(isConcat);
            liveViewRecordService.save(record);
        }
        return liveRecord;
    }

    /**
     * 申请成为主播
     *
     * @param info JdVerify
     * @return success
     */
    @Login
    @PostMapping("/applyLive")
    @ApiOperation("申请成为主播")
    public Success<Object> applyLive(
            @ApiParam JdVerify info
    ) {
        if (null == info.getId()) {
            verifyService.saveVerify(info);
        }
        String msg = liveApplyService.applyLive(info.getUserId());
        if (StringUtils.isNotBlank(msg)) {
            return Success.error(msg);
        }
        return Success.success(msg);
    }

    @Login
    @PostMapping("/applyLiveState")
    @ApiOperation("申请主播状态")
    public Success<LiveApplyState> applyLiveState(
            @ApiIgnore @LoginUser JdAppUser user
    ) {
        LiveApplyState applyState = new LiveApplyState();
        try {
            JdVerify verify = verifyService.lambdaQuery().eq(JdVerify::getUserId, user.getId()).one();
            JdLiveApply one = liveApplyService.lambdaQuery().eq(JdLiveApply::getUserId, user.getId()).one();
            applyState.setState(one.getState());
            applyState.setRemark(one.getRemark());
            applyState.setCardNumber(verify.getCardNumber());
            applyState.setName(verify.getName());
        } catch (Exception e) {
            return Success.success();
        }
        return Success.success(applyState);
    }

    @Login
    @PostMapping("/liveAgree")
    @ApiOperation("主播点赞")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "主播id", name = "liveId", dataType = "int", required = true),
    })
    public Success<String> liveAgree(
            @LoginUser @ApiIgnore JdAppUser user,
            Integer liveId
    ) {
        JdLiveAgree one = liveAgreeService.lambdaQuery()
                .eq(JdLiveAgree::getUserId, user.getId())
                .eq(JdLiveAgree::getLiveId, liveId).one();
        if (one == null) {
            one = new JdLiveAgree();
            one.setLiveId(liveId);
            one.setUserId(Integer.valueOf(user.getId()));
            liveAgreeService.save(one);
        } else {
            liveAgreeService.delete(one.getId());
        }
        return Success.success();
    }
}
